package com.im.chat.controller;

import com.im.chat.base.BasePagination;
import com.im.chat.controller.util.AdminDto;
import com.im.chat.controller.util.AdminRedisCache;
import com.im.chat.dto.ChatAdminDto;
import com.im.chat.dto.ChatRecordDto;
import com.im.chat.dto.ChatRecordSearchDto;
import com.im.chat.dto.ChatUserDto;
import com.im.chat.login.UserDto;
import com.im.chat.model.*;
import com.im.chat.service.*;
import com.im.chat.util.*;
import com.im.chat.util.biz.ImagePropertiesConfig;
import com.im.chat.util.cache.redis.RedisCache;
import com.im.chat.util.file.FileIOUtils;
import com.im.chat.util.jsonp.CommonConstant;
import com.im.chat.util.jsonp.Jsonp;
import com.im.chat.util.jsonp.Jsonp_data;
import com.im.chat.websocket.WebSocketConstant;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("chatUser")
public class ChatUserRestController {
    @Autowired
    private ChatRecordService chatRecordService;

    @Autowired
    private ChatSessionService chatSessionService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private AuthUserService authUserService;


    /**
     * 创建会话
     * @param sid
     * @param inviteCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createSession", method = RequestMethod.POST)
    public Object createSession(
            @RequestParam(name = "sid", required = true) String sid,
            @RequestParam(name = "inviteCode", required = false) String inviteCode
    ) {
        if (StringUtils.isEmpty(sid)){
            return Jsonp.paramError("sid不能为空!");
        }
        UserDto user = (UserDto) RedisCache.get(sid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long memberId = user.getMemberId();

        AuthUser authUser = authUserService.findByInviteCode(inviteCode);
        if(authUser==null){
            authUser = authUserService.findById(1L);//默认给id为1的管理员
        }
        Long adminId =  authUser.getId();

        ChatSession chatSession = new ChatSession();
        chatSession.setAdminId(adminId);
        chatSession.setMemberId(memberId);
        Member member = memberService.findById(memberId);
        if(member!=null){
            chatSession.setMemberName(member.getLoginName());//只存登录名
        }
        if(authUser!=null){
            chatSession.setAdminName(authUser.getLoginName());//只存登录名
        }

        chatSession.setStatus(WebSocketConstant.CHATSESSIOIN_STATUS_0);//0正常
        ChatSession chatSession1 = chatSessionService.getChatSessionByMemberIdAndAdminId(memberId,adminId);
        if(chatSession1!=null){
            return Jsonp.success();
        }else {
            long newChatId =  chatSessionService.insertChatSession(chatSession);
            if(newChatId>0){
                return Jsonp.success();
            }else{
                return Jsonp.error();
            }
        }

    }



    /**
     * 加载所有的会话信息
     * @param sid
     * @return
     */
    @RequestMapping(value = "/loadAllSessionInfos", method = RequestMethod.GET)
    @ResponseBody
    public Object loadAllSessionInfos(
            @RequestParam(name = "sid", required = true) String sid
    ) {
        if (StringUtils.isEmpty(sid)){
            return Jsonp.paramError("sid不能为空!");
        }
        UserDto user = (UserDto) RedisCache.get(sid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long memberId = user.getMemberId();


        List<Map<String, Object>> sessionList = new ArrayList<>();
        List<ChatSession> chatSessionList = chatSessionService.selectByMember(memberId);
        for (ChatSession chatSession : chatSessionList) {
            Map<String, Object> sessionInfoMap = new HashMap<>();
            List<ChatRecordDto> chatRecordDtos = ChatRecordDto.transDtos(chatRecordService.selectByMember(chatSession.getId(), "n", ChatConstant.RECORD_DEF_PAGE_SIZE));
            if (null != chatRecordDtos && chatRecordDtos.size() > 0) {
                sessionInfoMap.put("requestTimePoint", chatRecordDtos.get(0).getCreateTime());
            } else {
                sessionInfoMap.put("requestTimePoint", DateFormat.dateToString(new Date()));
            }
            //通过chatId 和adminId获取未读数量
            int unreadnum = chatRecordService.getMemberUnReadRecord(chatSession.getId(),memberId);
            sessionInfoMap.put("unreadnum", unreadnum);
//            sessionInfoMap.put("isTop", chatSession.getIsTop());
//            sessionInfoMap.put("topTime", DateFormat.dateToString(chatSession.getTopTime()));
//            sessionInfoMap.put("isCloseMSGRemind", chatSession.getIsCloseMsgRemind());
            sessionInfoMap.put("chatId", chatSession.getId());
            Collections.reverse(chatRecordDtos);
            sessionInfoMap.put("msgList", chatRecordDtos);
            sessionInfoMap.put("adminInfo",this.getChatAdminDto(chatSession.getAdminId()));
            sessionInfoMap.put("userInfo", this.getChatUserDto(chatSession.getMemberId()));
            sessionInfoMap.put("sessionStatus",chatSession.getStatus());//0:正常，1拉黑会话，2-关闭会话  //TODO:待修复？
            sessionList.add(sessionInfoMap);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("sessionList", sessionList);
        return Jsonp_data.success(resultMap);
    }


    public ChatAdminDto getChatAdminDto(Long adminId){
        ChatAdminDto chatAdminDto = new ChatAdminDto();
        AuthUser authUser = authUserService.findById(adminId);
        if(authUser!=null){
            chatAdminDto.setAdminId(adminId);
            chatAdminDto.setNickname(authUser.getNickName());
            chatAdminDto.setLoginName(authUser.getLoginName());
            if(authUser.getImgPath()!=null&&!authUser.getImgPath().equals("")){
                chatAdminDto.setPhoto(ImagePropertiesConfig.AUTHUSER_IMAGE_SERVER_PATH + authUser.getImgPath());
            }else{
                chatAdminDto.setPhoto("");
            }
        }
        return chatAdminDto;
    }
    public ChatUserDto getChatUserDto(Long memberid){
        ChatUserDto chatUserDto = new ChatUserDto();
        Member member = memberService.findById(memberid);
        if(member!=null){
            chatUserDto.setMemberId(memberid);
            chatUserDto.setNickname(member.getNickName());
            if(member.getImgPath()!=null&&!member.getImgPath().equals("")){
                chatUserDto.setPhoto(ImagePropertiesConfig.MEMBER_IMAGE_SERVER_PATH + "/"+ member.getImgPath());
            }else{
                chatUserDto.setPhoto("");
            }
            chatUserDto.setLoginName(member.getLoginName());
            chatUserDto.setAdminRemark(member.getAdminRemark());
        }
        return chatUserDto;
    }

    /**
     * 某个客户的历史聊天信息
     * @param sid
     * @param requestTimePoint
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/loadHistoryMsg", method = RequestMethod.GET)
    public Object loadHistoryMsg(
            @RequestParam(name = "sid", required = true) String sid,
            @RequestParam(name = "chatId", required = true) long chatId,
            @RequestParam(name = "requestTimePoint", required = true, defaultValue = "") String requestTimePoint,
            @RequestParam(name = "pageSize", required = false, defaultValue = PageConstant.APP_PAGE_SIZE + "") Integer pageSize
    ) {
        Map<String,Object> resultMap = new HashMap<>();
        if(!requestTimePoint.equals("")){

            if (StringUtils.isEmpty(sid)){
                return Jsonp.paramError("sid不能为空!");
            }
            UserDto user = (UserDto) RedisCache.get(sid);
            if (ObjectUtils.equals(null, user)){
                return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
            }
            long memberId = user.getMemberId();

            ChatSession chatSession = chatSessionService.findById(chatId);

            if(chatSession!=null) {
//                BasePagination<ChatRecord> page = new BasePagination<>();
//                page.setLimit(30);
                List<ChatRecordDto> chatRecordDtos = ChatRecordDto.transDtos(chatRecordService.selectByMember(chatId,requestTimePoint,ChatConstant.RECORD_DEF_PAGE_SIZE));

                resultMap.put("userInfo", this.getChatUserDto(chatSession.getMemberId()));
                resultMap.put("adminInfo",this.getChatAdminDto(chatSession.getAdminId()));
                Collections.reverse(chatRecordDtos);
                resultMap.put("msgList",chatRecordDtos);
                if(null!=chatRecordDtos&&chatRecordDtos.size()>0){
                    resultMap.put("requestTimePoint",chatRecordDtos.get(0).getCreateTime());
                }else{
                    resultMap.put("requestTimePoint",requestTimePoint);
                }
                resultMap.put("chatId",chatId);
            }
        }
        return Jsonp_data.success(resultMap);
    }


    @ResponseBody
    @RequestMapping(value = "/searchMessage", method = RequestMethod.POST)
    public Object searchMessage(
            @RequestParam(name = "sid", required = true) String sid,
            @RequestParam(name = "chatId", required = true) long chatId,
            @RequestParam(name = "keyWord", required = true) String keyWord,
            @RequestParam(name = "pageIndex", required = true, defaultValue = "1") Integer pageIndex,
            @RequestParam(name = "pageSize", required = false, defaultValue = PageConstant.APP_PAGE_SIZE + "") Integer pageSize
    ) {
        Map<String,Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(sid)){
            return Jsonp.paramError("sid不能为空!");
        }
        UserDto user = (UserDto) RedisCache.get(sid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }

        long memberId = user.getMemberId();
        ChatSession chatSession = chatSessionService.findById(chatId);
        if(chatSession!=null) {
            ChatAdminDto chatAdminDto = new ChatAdminDto();
            chatAdminDto.setAdminId(chatSession.getAdminId());
            chatAdminDto.setNickname(chatSession.getAdminName());
            chatAdminDto.setPhoto("");
            ChatUserDto chatUserDto  = new ChatUserDto();
            chatUserDto.setMemberId(user.getMemberId());
            chatUserDto.setNickname(user.getNickName());
            chatUserDto.setPhoto(user.getImgPath());
//            BasePagination<ChatRecord> page = new BasePagination<>();
//            page.setLimit(pageSize);
            List<ChatRecordSearchDto> chatRecordSearchDtoList = ChatRecordSearchDto.transDtos(chatRecordService.searchByMember(chatId,keyWord,pageIndex,pageSize));


            resultMap.put("userInfo",chatUserDto);
            resultMap.put("adminInfo",chatAdminDto);
            Collections.reverse(chatRecordSearchDtoList);
            resultMap.put("msgList",chatRecordSearchDtoList);
            resultMap.put("chatId",chatId);
            return Jsonp_data.success(resultMap);
        }else{
            return Jsonp.error();
        }

    }



    /**
     * 删除Message
     * @param sid
     * @param msgUniqueCodes
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delMessage", method = RequestMethod.POST)
    public Object delMessage(
            @RequestParam(name = "sid", required = false) String sid,
            @RequestParam(name = "msgUniqueCodes", required = true) String msgUniqueCodes,
            @RequestParam(name = "chatId", required = true) long chatId
    ) {
        if (StringUtils.isEmpty(sid)){
            return Jsonp.paramError("sid不能为空!");
        }
        UserDto user = (UserDto) RedisCache.get(sid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }

        int i = chatRecordService.delRecords(chatId,msgUniqueCodes);
        if(i>0){
            System.out.println("delMessage请求数据成功");
        }else{
            System.out.println("delMessage请求数据失败");
        }
        return Jsonp.success();
    }

    /**
     * 消息已读
     * @param sid
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/readMessage", method = RequestMethod.POST)
    public Object readMessage(
            @RequestParam(name = "sid", required = false) String sid,
            @RequestParam(name = "chatId", required = true) Long chatId
    ) {
        if (StringUtils.isEmpty(sid)){
            return Jsonp.paramError("sid不能为空!");
        }
        UserDto user = (UserDto) RedisCache.get(sid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long memberId = user.getMemberId();
        int i = chatRecordService.updateMemberUnReadRecord(chatId,memberId);
        if(i>0){
            System.out.println("readMessage请求数据成功");
        }else{
            System.out.println("readMessage请求数据失败");
        }
        return Jsonp.success();
    }


    /**
     *
     * @param sid
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public Object fileUpload(
            @RequestParam(value="sid",required=true) String sid,
            //@RequestParam("widthToHeight") String widthToHeights,//以逗号分割，
            @RequestParam("file") MultipartFile[] file) {
        try {

            if (StringUtils.isEmpty(sid)){
                return Jsonp.paramError("sid不能为空!");
            }
            UserDto user = (UserDto) RedisCache.get(sid);
            if (ObjectUtils.equals(null, user)){
                return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
            }

            ChatUserDto chatUserDto  = new ChatUserDto();
            chatUserDto.setMemberId(user.getMemberId());
            chatUserDto.setNickname(user.getNickName());
            chatUserDto.setPhoto(user.getImgPath());

            //String widthToHeight [] = widthToHeights.split(",");
            List<String> widthToHeightList = new ArrayList<>();
            List<String> idList = new ArrayList<>();
            List<String> imgList = new ArrayList<>();
            for (int i = 0; i < file.length; i++) {
                boolean writeFileFromIS = false;
                MultipartFile multipartFile = file[i];
                InputStream inputStream = multipartFile.getInputStream();
                if (inputStream != null) {
                    Date now = new Date();
                    // 获取文件的名字
                    String filename = multipartFile.getOriginalFilename();
                    String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                    long fileSize = multipartFile.getSize();
                    long timeMillis = System.currentTimeMillis();
                    String TIME_PATH = DateFormat.dateToYearMonth(now);
                    String articlePath = "chat";
                    // 文件类型目录+时间目录+时间戳名+文件后缀名
                    String FilePostfix = articlePath + "/" + TIME_PATH + "/" + timeMillis + "." + suffix;
                    // 首页功能管理目录文件路径（根目录+文件后缀）
                    String filePath = ImagePropertiesConfig.RESOURCE_PATH + FilePostfix;
                    writeFileFromIS = FileIOUtils.writeFileFromIS(filePath, inputStream);
                    if (writeFileFromIS) {
                        String imageUrl = ImagePropertiesConfig.RESOURCE_SERVER_PATH + FilePostfix;
                        Resource resource = new Resource();
                        resource.setArticleCode("MemberUpload");
                        resource.setArticleValue(chatUserDto.getMemberId()+"");
                        resource.setFileFix(suffix);
                        resource.setFileMixName(timeMillis + "." + suffix);
                        resource.setFileName(filename);
                        resource.setFileSize(fileSize);
                        resource.setSource(3);
                        resource.setResCode(RandomNumUtil.getCharacterAndNumber(ChatConstant.RESOURCE_RESCODE_LEN));
                        resource.setTag("chat");
                        //存储相对路径
                        resource.setUrl(ImagePathUtil.getFileName(filePath));
                        resource.setCreateTime(now);
                        resource.setFileType(ResourceUtil.getFileTypeBySuffix(suffix));
                        resource.setIsDel(ChatConstant.IS_DEL_N);
                        //1上传  2下载
                        resource.setType(ChatConstant.RESOURCE_UPLOAD);
                        //resource.setWidthToHeight(widthToHeight[i]);
                        resourceService.add(resource);
                        //widthToHeightList.add(widthToHeight[i]);
                        idList.add(resource.getId()+"");
                        imgList.add(imageUrl);

                    } else {
                        return Jsonp.error(multipartFile.getOriginalFilename() + "上传失败");
                    }
                }
            }

            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("idList", idList);
            resultMap.put("imgList", imgList);
            //resultMap.put("widthToHeightList", widthToHeightList);
            return Jsonp_data.success(resultMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Jsonp.error("文件上传异常,请稍后重试！");
    }
}
